<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/11/21
 * Time: 19:29
 * 用户登录验证
 */
include_once 'admin_global.php'; //加载后台调用类文件

//判断用户是否单击了登录按钮
if (isset($_POST['submit'])) {
    //检测用户名密码
    $userName = trim($_POST['username']); //获取用户输入的用户名
    $userPassword = trim($_POST['password']); //获取用户输入的密码
    //使用函数对用户名密码进行处理，防止SQL注入
    $userName = strip_tags($userName); //strip_tags() 函数剥去字符串中的 HTML、XML 以及 PHP 的标签
    $userName = htmlspecialchars($userName); //htmlspecialchars() 函数把预定义的字符(如“ ‘ <  > & )转换为 HTML 实体。
    $userName = addslashes($userName); //addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。
    $password = strip_tags($userPassword);
    $password = htmlspecialchars($password);
    $password = addslashes($password);
    $password = sha1($password);
    $query = $db->select("admin", "*", "userName='$userName' AND userPassword='$password'");
    $num = $db->db_num_rows();
    if ($num != 0) {
        //检测用户名是否可用
        $result = $db->fetch_array();
        if ($result['userEnabled'] == 1) {
            //判断验证码
            $code = trim($_POST['code']);
            $code = strip_tags($code);
            $code = htmlspecialchars($code);
            $code = strtolower($code);
            $captchaCode = strtolower($_SESSION['captcha']);
            if ($code == $captchaCode) {
                //准备登陆后台首页
                //1.存储SESSION变量
                $_SESSION['uid'] = $result['userID'];
                $_SESSION['userName'] = $result['userName'];
                $_SESSION['userType'] = $result['userType'];
                $_SESSION['shell'] = sha1($result['userName'] . $result['userPassword'] . "PSY");
                //2.把用户登录的时间和IP写入admin表
                $recentLoginTime = time();
                $recentLoginIP = $db->getip();
                $db->update("admin", "recentLoginTime=$recentLoginTime,recentLoginIP='$recentLoginIP'", "userName='$userName'");
                //3.跳转到后台首页
                echo "<script>location.href='index.php';</script>";
            } else {
                echo "<script>alert('验证码错误！');location.href='login.php';</script>";
            }
        } else {
            echo "<script>alert('用户被禁用！');location.href='login.php';</script>";
        }
    } else {
        echo "<script>alert('用户名密码错误！');location.href='login.php';</script>";
        //echo "用户名密码错误！";
        //header("Refresh:3;url=login.php");        //等待3秒后跳转
    }
}
